<template>
  <div class="w-full custom-flex flex px-[12px] pb-[12px]">
    <!-- 左边侧边栏 -->
    <div class="left_menu w-[288px] h-full mr-[12px]">
      <div class="px-[8px]">
        <div class="upload_button my-[12px] flex items-center" @click="onUpload(false)">
          <svg-icon name="upload" class="w-[16px] h-[16px] mr-[8px]" style="fill: rgb(26, 102, 255);" />
          新建清洗任务
        </div>
        <!-- <div class="flex items-center">
          <el-icon class="cursor-pointer"><Fold /></el-icon>
        </div> -->
        <el-input class="my-[8px]" v-model="search" clearable placeholder="请输入" :prefix-icon="Search"
          @clear="onSearchInput" @keyup.enter="onSearchInput">
        </el-input>
      </div>
      <div class="left_tab flex items-center justify-between py-[10px]">
        <div v-for="item in tabList" :key="item.id" class="w-1/2 flex items-center justify-center cursor-pointer"
          :class="{
            tabItem: activeName == item.id,
          }" @click="onTabClick(item)">
          {{ item.name }}
        </div>
      </div>
      <div class="menuLine">
        <div class="px-[8px] overflow-y-hidden" v-for="item in menuList" :key="item.date">
          <div class="dateLine">{{ getDayName(item.createdTime) }}</div>
          <template v-for="it in item.list" :key="it.name">
            <div v-if="!it.isRename" :class="`menuItem ${selectData.id == it.id ? 'activeMenu' : ''}`"
              @click="onSelect(it)">
              <div class="flex items-center truncate">
                <img :src="it.id == selectData.id ? activeFileIcon : fileIcon" alt=""
                  class="w-[20px] h-[20px] mr-[8px]" />
                <span class="truncate"> {{ it.name }}</span>
              </div>
              <el-popover placement="bottom-end" title="" :width="150" trigger="hover" content="" :show-arrow="false">
                <template #reference>
                  <div>
                    <div class="iconLine">
                      <el-icon class="text-[#000]">
                        <MoreFilled />
                      </el-icon>
                    </div>
                  </div>
                </template>
                <div class="p-[4px]">
                  <div class="px-[12px] py-[10px] popver_item" @click="onClickRename(it)">
                    重命名
                  </div>
                  <div class="px-[12px] py-[10px] popver_item" @click="onDetele(it.id)">
                    删除
                  </div>
                </div>
              </el-popover>
            </div>
            <div v-if="it.isRename && isRename" class="activeMenu p-[8px] flex items-center"
              v-on-click-outside="handleRenameOutsideClick" @click.stop>
              <el-input style="width: 216px" clearable class="input_rename" v-model="reName" placeholder="请输入名称（1-40位）"
                maxlength="40" minlength="1" @click.stop @input="validateRenameInput" />
              <img src="../../../assets/images/check_icon.png" class="w-[32px] h-[32px] ml-[8px] cursor-pointer"
                @click.stop="handleRename(it)" />
            </div>
          </template>
        </div>
      </div>
    </div>
    <!-- 表格模块/上传模块 -->
    <!-- <component :is="coms[dialogType]"></component> -->
    <!-- <div v-show="isUpload" class="upload-main">
      <Upload ref="upLoadRef" :selectData="selectData" @onChangeMenu="onChangeMenu" />
    </div> -->
    <div v-show="isUpload" class="start-main">
      <div class="upload-header">
        <div class="left-name">
          <div class="show-name" v-show="!isEditCaseName">{{ currentCaseName }}
            <el-icon size="16" color="#000000" style="cursor: pointer;" @click="editCaseName()">
              <Edit />
            </el-icon>
          </div>
          <div class="edit-name flex items-center" v-show="isEditCaseName">
            <el-input style="width: 216px" clearable class="input_rename" v-model="currentCaseName" placeholder="请输入名称（1-40位）"
              maxlength="40" minlength="1" @click.stop />
            <img src="../../../assets/images/check_icon.png" class="w-[32px] h-[32px] ml-[8px] cursor-pointer"
             @click="isEditCaseName = false" />
          </div>
        </div>

        <div class="right-action flex items-center">
          <el-input v-model="fileNameSearch" style="width: 272px" class="responsive-input" placeholder="请输入" :suffix-icon="Search"/>
          <el-button icon="CirclePlus" size="large">共享协作</el-button>
          <el-button size="large">导出全部</el-button>
          <el-button icon="DocumentChecked" type="primary" size="large">研判分析</el-button>
        </div>
      </div>

      <div class="no-list-mian" v-show="fileListNoData">
        <div class="no-list-content">
          <img src="../../../assets/images/no_file_data.png" class="no-data-img" />
          <div class="no-data-word">请先上传文件</div>
          <el-button style="margin: 0 auto;" type="primary">去上传文件</el-button>
        </div>
      </div>
    </div>
    <!-- 解密解析完成解析 -->
    <div class="table-main" v-show="isTable">
      <Table ref="tableRef" @onUpload="onUpload" :selectData="selectData" @handleRename="changRename" />
    </div>
  </div>
</template>
<script setup>
// import { ClickOutside as vClickOutside } from "element-plus";
import { vOnClickOutside } from '@vueuse/components'
import dayjs from "dayjs";
import fileIcon from "../../../assets/images/file_icon.png";
import activeFileIcon from "../../../assets/images/active_file_icon.png";
import { Search } from "@element-plus/icons-vue";
import Upload from "./component/upload.vue";
import Table from "./component/table.vue";
import { getDayName, getformat } from "@/utils/index.js";
const tableRef = ref();
const isTable = ref(false);
const isUpload = ref(true);
const upLoadRef = ref();
// const dialogType = ref(1);
const drawerRef = ref();
const search = ref("");
const activeName = ref(1);
const selectData = ref({});
const isRename = ref(false);
const reName = ref(""); //重命名
const tabList = ref([
  {
    name: "我的",
    id: 1,
  },
  {
    name: "共享",
    id: 2,
  },
]);
const menuList = ref([]);
const initList = ref([]);
const currentCaseName = ref('202510161553')
const isEditCaseName = ref(false)
const fileNameSearch = ref('')
const fileListNoData = ref(true)
const handleClickOutside = () => {
  isRename.value = false;
  menuList.value.length &&
    menuList.value.forEach((item) => {
      item.list.forEach((it) => {
        it.isRename = false;
      });
    });
};

const handleRenameOutsideClick = () => {
  console.log('点击重命名区域外部，退出编辑状态');
  isRename.value = false;
  menuList.value.length &&
    menuList.value.forEach((item) => {
      item.list.forEach((it) => {
        it.isRename = false;
      });
    });
  reName.value = '';
};
const onClickRename = (it) => {
  // 关闭其他的重命名状态
  if (isRename.value) return;

  // 先设置重命名状态，再设置输入框的值
  isRename.value = true;
  it.isRename = true;
  reName.value = it.name;

  console.log('开启重命名模式:', it.name, 'isRename:', isRename.value);
};

// 验证重命名输入框长度
const validateRenameInput = (value) => {
  if (value && value.length < 1) {
    reName.value = value.substring(0, 1);
  }
};
const changRename = (name) => {
  reName.value = name;
  handleRename(selectData.value);
};
//  目录重命名
const handleRename = async (row) => {
  console.log('开始重命名:', row.name, '新名称:', reName.value);

  // 验证输入长度
  if (!reName.value || reName.value.trim().length === 0) {
    ElMessage.error('名称不能为空');
    return;
  }

  if (reName.value.trim().length > 40) {
    ElMessage.error('名称长度不能超过40位');
    return;
  }

  let [err, res] = await api.getRename({
    caseId: row.id,
    name: reName.value.trim(),
  });
  if (err) return;

  console.log('重命名成功，关闭重命名状态');
  isRename.value = false;

  await queryList();
  selectData.value = initList.value.find((item) => item.id == row.id) || {};
  ElMessage.success({
    message: "重命名成功",
    showClose: true,
  });
};
// 删除目录
const onDetele = async (id) => {
  const close = Delmessage({
    title: "删除确认",
    content: "是否确认删除本条记录？",
    submitText: "删除",
    cancel() {
      close();
    },
    submit: antiShake(async () => {
      // 共享的案件删除只删除分享的记录，不删除案件
      const apiType =
        activeName.value == 2 ? api.delSharefile(id) : api.delfile(id);
      let [err, res] = await apiType;
      if (err) return;
      await queryList();
      ElMessage.success({
        message: "删除成功",
        showClose: true,
      });
      // 判断删除的目录是否存在于当前列表中;
      const flag = initList.value.some((item) => item.id == id);
      if (!flag) {
        selectData.value = initList.value?.[0] || {};
        if (!selectData.value.id) {
          isTable.value = false;
          isUpload.value = true;
        }
      }
      close();
    }),
  });
};
const onChangeMenu = async (flag) => {
  activeName.value = 1;
  await queryList();
  // 新建上传目录拿取第一条
  if (flag) selectData.value = initList.value?.[0];
  if (!flag)
    selectData.value = initList.value.find((item) => item.id == row.id) || {};
  isUpload.value = false;
  isTable.value = true;
};
// 新建上传
const onUpload = (flag) => {
  isUpload.value = true;
  isTable.value = false;
  upLoadRef.value.openUpload();
  if (!flag) selectData.value = {};
};
// 搜索
const onSearchInput = () => {
  const arr = initList.value.filter((item) => {
    // const time = dayjs(item.createdTime).format("YYYYMMDDHHmmss");
    // return time.includes(search.value);
    return item.name.includes(search.value);
  });
  menuList.value = getformat(arr);
};
// tab切换
const onTabClick = (item) => {
  activeName.value = item.id;
  tableRef.value.resetActiveId();
  queryList();
};
// 目录切换
const onSelect = (item) => {
  selectData.value = item;
  isTable.value = true;
  isUpload.value = false;
  tableRef.value.resetActiveId();
  // reName.value = item.name;
};
const openDrawer = () => {
  drawerRef.value.onOpen();
};
// 获取目录数据
const queryList = async () => {
  const apiType = activeName.value == 1 ? api.getList() : api.getShareList();
  let [err, res] = await apiType;
  if (err) return;
  initList.value = res.data || [];
  menuList.value = getformat(res?.data);
  // if (selectData.id) {
  //   selectData.value =
  //     initList.value.find((item) => item.id == selectData.id) || {};
  // }
};
const getList = async () => {
  let [err, res] = await api.getShareList();
  if (err) return;
  initList.value = res.data;
  menuList.value = getformat(res.data);
};

const editCaseName = () => {
  isEditCaseName.value = true
}

onMounted(() => {
  queryList();
  const btn = document.querySelector(".custom-flex");
  btn.addEventListener("click", (event) => {
    // 如果点击的是重命名输入框或其内部元素，不关闭重命名状态
    if (event.target.closest('.input_rename') ||
      event.target.closest('.activeMenu') ||
      event.target.closest('input')) {
      return;
    }

    isRename.value = false;
    tableRef.value.handleclose();
    menuList.value.length &&
      menuList.value.forEach((item) => {
        item.list.forEach((it) => {
          it.isRename = false;
        });
      });
  });
});
</script>
<style lang="scss" scoped>
.iconLine {
  visibility: hidden; // 默认隐藏，但保持空间
  width: 32px;
  height: 32px;
  display: flex; // 改为 flex 布局
  align-items: center; // 垂直居中
  justify-content: center; // 水平居中
  color: #181818;
  border-radius: 4px;
  cursor: pointer;
  // 去掉悬浮背景色
}

.input_rename {
  border: 1px solid rgba(11, 73, 217, 1);
  border-radius: 4px;
  box-shadow: 0px 0px 0px 2px rgba(26, 102, 255, 0.3);
  background: rgba(255, 255, 255, 1);
}

.popver_item {
  color: #181818;
  font-size: 16px;
  padding: 8px;
  cursor: pointer;

  &:hover {
    background: rgba(26, 102, 255, 0.1);
  }
}

.custom-flex {
  flex: 1;
  overflow: hidden;
}

.left_menu {
  display: flex;
  flex-direction: column;
  border-radius: 12px;
  // flex-shrink: 0;
  min-width: 240px;
  // background-image: url(images/left_bg.png);
  // background-position: bottom left;
  // background-repeat: no-repeat;
  background: linear-gradient(180deg,
      rgba(255, 255, 255, 1),
      rgba(255, 255, 255, 0.4) 100%);

  .upload_button {
    cursor: pointer;
    width: fit-content;
    color: rgba(26, 102, 255, 1);
    padding: 10px 40px;
    border-radius: 16px;
    background: rgba(26, 102, 255, 0.2);
  }

  .left_tab {
    border-bottom: 1px solid rgba(232, 232, 232, 1);
    color: rgba(0, 0, 0, 0.6);
    position: relative;

    .tabItem {
      color: rgba(26, 102, 255, 1);

      &:after {
        content: "";
        width: 48%;
        height: 2px;
        background-color: #1269eb;
        display: block;
        position: absolute;
        bottom: -1px;
        border-bottom: 2px solid rgba(26, 102, 255, 1);
      }
    }
  }

  .dateLine {
    padding: 14px 0 4px 8px;
    color: rgba(0, 0, 0, 0.6);
    font-size: 14px;
  }

  .menuLine {
    flex: 1;
    overflow: auto;
  }

  .menuItem {
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: rgba(0, 0, 0, 0.9);
    font-weight: bold;
    padding: 16px 8px;
    border-radius: 8px;
    cursor: pointer;

    .menu-name {
      margin-left: 8px;
    }

    &:hover {
      // padding: 12px 8px;
      // border-radius: 8px;
      background: rgba(26, 102, 255, 0.1);

      .iconLine {
        visibility: visible; // 使用 visibility 显示
      }
    }
  }

  .activeMenu {
    // padding: 12px 8px;
    color: #1a66ff;
    // border-radius: 8px;
    background: rgba(26, 102, 255, 0.1);

    .iconLine {
      visibility: visible; // 使用 visibility 显示，保持空间
    }
  }
}

.table-main {
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  flex: 1;
  background: linear-gradient(180deg,
      rgba(255, 255, 255, 1),
      rgba(255, 255, 255, 0.4) 100%);
}

.upload-main {
  flex: 1;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(180deg,
      rgba(255, 255, 255, 1),
      rgba(255, 255, 255, 0.4) 100%);
}

.start-main{
  flex: 1;
  border-radius: 8px;
  background: linear-gradient(180deg,
      rgba(255, 255, 255, 1),
      rgba(255, 255, 255, 0.4) 100%);

  .upload-header{
    width: 100%;
    height: 64px;
    border-bottom: 1px solid #E8E8E8;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    padding: 0 12px;

    .left-name{
      // display: flex;
      // align-items: center;
      // gap: 8px;

      .show-name{
        font-family: Microsoft YaHei;
        font-size: 20px;
        font-weight: 700;
        display: flex;
        align-items: center;
        gap: 8px;
      }
    }

    .right-action{
      gap: 16px;
    }
  }

  .no-list-mian{
    height: calc(100% - 64px);
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-around;

    .no-list-content{
      width: fit-content;
      height: fit-content;
      text-align: center;

      .no-data-img{
        width: 160px;
        height: 160px;
        margin-bottom: 8px;
      }

      .no-data-word{
        font-family: Microsoft YaHei;
        font-size: 14px;
        font-weight: 400;
        text-align: center;
        margin-bottom: 32px;
      }
    }
  }
}
</style>